package com.xiaozhen.blog.controller.admin;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.blog.entity.Blog;
import com.xiaozhen.blog.entity.Type;
import com.xiaozhen.blog.entity.User;
import com.xiaozhen.blog.service.BlogService;
import com.xiaozhen.blog.service.TagService;
import com.xiaozhen.blog.service.TypeService;
import com.xiaozhen.blog.service.impl.LoginUser;
import com.xiaozhen.blog.utils.MinioUtils;
import com.xiaozhen.blog.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @create 2023-05-03 12:12
 */
@Controller
@RequestMapping("/admin")
public class BlogAdminController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private TagService tagService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 小圳博客管理后台
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('user','admin')")
    @GetMapping("/blogs")
    public String Blogs(@RequestParam(value = "page", required = false) Long page,
                        Model model) {
        // 1. 分类查询初始化
        // 如果没有传入参数，那么我们把page定义为第 1 页
        if (page == null) {
            page = 1L;
        }
        // 创建对象，传递分页相关参数，每页记录数为 100
        Page<Blog> pageParam = new Page<>(page, 6);

        // 2. 获取所有的分类
        List<Type> typeList = typeService.typeList();

        // 3. 获取所有博客

        model.addAttribute("types", typeList);
        model.addAttribute("page", blogService.blogPage2(pageParam));
        return "admin/blogs";
    }

    /**
     * 点击新增博客
     *
     * @param model
     * @return
     */
    @PreAuthorize("hasAnyAuthority('user','admin')")
    @GetMapping("/blogs/input")
    public String input(Model model) {
        model.addAttribute("types", typeService.typeList());
        model.addAttribute("tags", tagService.tagList());
        model.addAttribute("blog", new Blog());
        return "admin/blogs-input";
    }

    /**
     * 发布博客
     *
     * @param blog
     * @param attributes
     * @return
     */
    @PreAuthorize("hasAnyAuthority('user','admin')")
    @PostMapping("blogs")
    public String post(Blog blog, RedirectAttributes attributes) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = authentication.getName();
        String redisKey = "login:" + userId;
        LoginUser loginUser = JSON.parseObject(redisCache.getCacheObject(redisKey), LoginUser.class);
        User user = loginUser.getUser();
        Long id = user.getId();
        blog.setUserId(id);

        boolean b;
        if (blog.getId() == null) {
            b = blogService.save(blog);
        } else {
            b = blogService.updateById(blog);
        }
        if (b == false) {
            attributes.addFlashAttribute("message", "操作失败");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }
        return "redirect:/admin/blogs";
    }

    @PreAuthorize("hasAnyAuthority('user','admin')")
    @GetMapping("/upload")
    public String uploadPicture(Model model) {
        model.addAttribute("headerUrl", "请上传图片");
        return "admin/upload";
    }

    @PreAuthorize("hasAnyAuthority('user','admin')")
    @PostMapping("/upload")
    public String uploadPicture(MultipartFile headerImage,
                                Model model) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        // 1. 检查参数
        if (headerImage == null || headerImage.getSize() == 0) {
            model.addAttribute("error", "传入文件错误！");
        }
        // 2. 上传文件到 minio 中
        // 获取用户上传图片的文件名
        String filename = headerImage.getOriginalFilename();
        // TODO 获取用户上传的图片路径
        File tempFile = File.createTempFile(filename, "");
        headerImage.transferTo(tempFile);
        String filePath = tempFile.getAbsolutePath();
        // 更新当前博客首页图片的路径
        String headerUrl = MinioUtils.uploadFile("blogheader", filename,filePath);
        model.addAttribute("headerUrl", headerUrl);
        return "admin/upload";
    }


    /**
     * 编辑博客
     *
     * @param id
     * @param model
     * @return
     */
    @PreAuthorize("hasAnyAuthority('user','admin')")
    @GetMapping("blogs/{id}/update")
    public String updateBlog(@PathVariable Long id, Model model) {
        model.addAttribute("types", typeService.typeList());
        model.addAttribute("tags", tagService.tagList());
        model.addAttribute("blog", blogService.getById(id));
        return "admin/blogs-input";
    }

    /**
     * 删除博客
     *
     * @param id
     * @param attributes
     * @return
     */
    @PreAuthorize("hasAuthority('admin')")
    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes) {
        blogService.removeById(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/blogs";
    }
}
